<template>
  <div>
    <a-form :form="detailForm">
      <a-card style="margin-top: 20px">
        <div class="title_detail">{{ pageType == "add" ? "新增商品" : "编辑商品" }}</div>
        <a-divider />
        <div class="title_part">1.基本信息</div>
        <a-form-item
          label="商品标题"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input v-model="detailForm.title" placeholder="请输入商品标题"></a-input>
        </a-form-item>
        <a-form-item
          label="商品名称"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input v-model="detailForm.name" placeholder="请输入商品名称"></a-input>
        </a-form-item>
        <a-form-item
          label="商品中文名"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input v-model="detailForm.cnName" placeholder="请输入商品中文名"></a-input>
        </a-form-item>
        <a-form-item
          label="预报英文名"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input
            v-model="detailForm.predictionName"
            placeholder="请输入预报英文名"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="SPU编码"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input
            v-model="detailForm.spuCode"
            :disabled="pageType == 'edit'"
            placeholder="请输入SPU编码"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="商品分类"
          required
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          v-if="categoryTreeData.length > 0"
        >
          <a-tree-select
            v-model="detailForm.categoryId"
            style="width: 100%"
            :tree-data="categoryTreeData"
            :replaceFields="{
              children: 'children',
              title: 'name',
              key: 'id',
              value: 'id',
            }"
            show-checked-strategy="SHOW_ALL"
            search-placeholder="Please select"
          ></a-tree-select>
        </a-form-item>
        <a-form-item
          label="商品排序"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
          required
        >
          <a-input-number
            v-model="detailForm.sort"
            placeholder="请输入商品排序"
          ></a-input-number>
        </a-form-item>
      </a-card>
      <a-card style="margin-top: 20px">
        <div class="title_part">2.描述信息</div>
        <a-form-item label="展示图片" :labelCol="{ span: 3 }" :wrapperCol="{ span: 12 }">
          <div class="flex-aic">
            <div>
              <UploadImg
                listType="picture-card"
                :max="1"
                :imgTips="'只能上传.png,.jpg,.jpeg文件'"
                v-model="detailForm.mainImg"
              ></UploadImg>
              <div class="img_title">主图</div>
            </div>
            <div style="margin-left: 20px">
              <UploadImg
                listType="picture-card"
                :max="1"
                :imgTips="'只能上传.png,.jpg,.jpeg文件'"
                v-model="detailForm.subImg"
              ></UploadImg>
              <div class="img_title">副图</div>
            </div>
          </div>
        </a-form-item>
        <a-form-item label="商品图片" :labelCol="{ span: 3 }" :wrapperCol="{ span: 12 }">
          <UploadImg
            listType="picture-card"
            :max="1"
            :imgTips="'只能上传.png,.jpg,.jpeg文件'"
            v-model="detailForm.detailImg"
          ></UploadImg>
        </a-form-item>
        <a-form-item label="视频" :labelCol="{ span: 3 }" :wrapperCol="{ span: 12 }">
          <UploadImg
            listType="text"
            :max="1"
            :FileType="'video/mp4'"
            :imgFile="'video'"
            :imgTips="'只能上传.mp4文件'"
            v-model="detailForm.videoUrl"
          ></UploadImg>
          <video width="320" height="240" controls v-if="detailForm.videoUrl?.length >0">
            <source :src="detailForm.videoUrl" type="video/mp4" />
          </video>
        </a-form-item>
        <a-form-item label="物流模板" required :labelCol="{ span: 3 }" :wrapperCol="{ span: 12 }">
          <a-select v-model="detailForm.tmplCode">
            <a-select-option
              v-for="(item, index) in templateList"
              :key="index"
              :value="item.key"
            >
              {{ item.value }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="商品描述"
          :labelCol="{ span: 3 }"
          :wrapperCol="{ span: 12 }"
        >
          <Editor
            v-if="hasLoaded"
            :innerhtml="editorDetl"
            @editorChange="editorChange"
          ></Editor>
        </a-form-item>
        <a-form-item label="SKU" :labelCol="{ span: 3 }" :wrapperCol="{ span: 12 }">
          <div class="flex-aic-tops">
            <div>SIZE</div>
            <a-select
              style="margin-left: 10px"
              v-model="selectSize"
              mode="multiple"
              @change="sizeSelectChange"
            >
              <a-select-option
                v-for="(item, index) in sizeLists"
                :key="index"
                :value="item.id"
              >
                {{ item.value }}
              </a-select-option>
            </a-select>
          </div>
          <div class="flex-aic">
            <div>COLOR</div>
            <a-select
              style="margin-left: 10px"
              v-model="selectColor"
              mode="multiple"
              @change="colorSelectChange"
            >
              <a-select-option
                v-for="(item, index) in colorLists"
                :key="index"
                :value="item.id"
              >
                {{ JSON.parse(item.value)?.rgb + "-" + JSON.parse(item.value)?.rgbValue }}
              </a-select-option>
            </a-select>
          </div>
        </a-form-item>
        <a-form-item label="销售规格" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
          <a-table
            :scroll="{ x: 1100, y: 600 }"
            :rowKey="(it, index) => it.id + index"
            :columns="skuColumns"
            :dataSource="skuLists"
            :pagination="false"
            binvested
          >
            <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
            <span slot="color" slot-scope="text, record">{{ record.color }}</span>
            <span slot="size" slot-scope="text, record">{{ record.size }}</span>
            <span slot="skuCode" slot-scope="text, record">{{ record.skuCode }}</span>
            <a-input-number
              slot="sort"
              slot-scope="text, record"
              v-model="record.sort"
            ></a-input-number>
            <a-input
              slot="cost"
              slot-scope="text, record"
              v-model="record.cost"
            ></a-input>
            <a-input
              slot="onlinePrice"
              slot-scope="text, record"
              v-model="record.onlinePrice"
            ></a-input>
            <a-input
              slot="offlinePrice"
              slot-scope="text, record"
              v-model="record.offlinePrice"
            ></a-input>
            <a-input
              slot="weight"
              slot-scope="text, record"
              v-model="record.weight"
            ></a-input>
            <a-input
              slot="volume"
              slot-scope="text, record"
              v-model="record.volume"
            ></a-input>
            <a-switch slot="status" slot-scope="text, record" v-model="record.status" />
          </a-table>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="save">保存商品</a-button>
        </a-form-item>
      </a-card>
    </a-form>
  </div>
</template>
<script>
import Editor from "@/comps/Editor";
import { deepCopy } from "@/utils/util";
import UploadImg from "@/comps/UploadImg.vue";
import { baseTemplate } from "@/api/logistic";
import { attributeValue, categoryTree, productDetail, productAdd } from "@/api/product";
export default {
  components: { Editor, UploadImg },
  data() {
    return {
      form: this.$form.createForm(this, { name: "addProd" }),
      editorDetl: "",
      hasLoaded:false,
      pageType: "add",
      productId: "",
      detailForm: {
        title: "",
        name:'',
        cnName: "",
        predictionName: "",
        categoryId: "",
        spuCode: "",
        sort: 0,
        mainImg: "",
        subImg: "",
        detailImg: "",
        videoUrl: "",
        tmplCode: "",
      },
      templateList: [],
      AllAttributes: [],
      afterHandleAttrData: [],
      colorLists: [],
      selectColor: [],
      sizeLists: [],
      selectSize: [],
      shoeLists:[],
      
      categoryTreeData: [],
      skuColumns: [
        { title: "批量填充", scopedSlots: { customRender: "index" } },
        { title: "color-all", scopedSlots: { customRender: "color" } },
        { title: "size-all", scopedSlots: { customRender: "size" } },
        { title: "SkuCode", scopedSlots: { customRender: "skuCode" } },
        { title: "采购成本", scopedSlots: { customRender: "cost" } },
        { title: "线上价格", scopedSlots: { customRender: "onlinePrice" } },
        { title: "线下价格", scopedSlots: { customRender: "offlinePrice" } },
        { title: "是否下架", scopedSlots: { customRender: "status" } },
        { title: "重量(kg)", scopedSlots: { customRender: "weight" } },
        { title: "体积(cm^3)", scopedSlots: { customRender: "volume" } },
      ],
      originSkuList: [],
      skuLists: [],
    };
  },
  async created() {
    let { type = "add", id = "" } = this.$route.query;
    this.pageType = type;
    this.productId = id;
    await this.getBaseTemplate();
    await this.getCategoryList();
    await this.getAttributeVals();
    
  },
  async mounted(){
    if (this.pageType == "edit") {
      await this.getDetail(this.productId);
    }else{
      this.hasLoaded = true
    }
  },
  computed: {},
  // watch: {
  //   'selectSize': {
  //     handler(newVal, oldVal) {
  //       newVal&& this.attrCombination(newVal,'Size')
  //     },
  //     immediate: true,
  //     deep: true
  //   },
  //   'selectColor': {
  //     handler(newVal, oldVal) {
  //       newVal&& this.attrCombination(newVal,'Color')
  //     },
  //     immediate: true,
  //     deep: true
  //   },
  // },
  methods: {
    async getBaseTemplate() {
      let res = await baseTemplate();
      this.templateList = res?.data;
    },
    async getDetail(id) {
      let res = await productDetail(id);
      let {
        title = "",
        name = '',
        cnName = "",
        predictionName = "",
        categoryId = "",
        description = "",
        spuCode = "",
        sort = 0,
        mainImg = "",
        subImg = "",
        detailImg = "",
        videoUrl = "",
        tmplCode = "",
        skus = [],
        attrValues = [],
      } = res?.data;
      this.detailForm = {
        title,
        name,
        cnName,
        predictionName,
        categoryId,
        spuCode,
        sort,
        mainImg,
        subImg: subImg?.[0] == ''? '':subImg,
        detailImg: detailImg?.[0] == ''? '':detailImg,
        videoUrl: videoUrl?.[0] == ''? '':videoUrl,
        tmplCode,
      };
      this.editorDetl = description;

      this.hasLoaded = true
      this.afterHandleAttrData = attrValues;
      let choosedColors = [],
        choosedSizes = [];
      let temChildrenColor = attrValues.filter((item) => {
          return item.name == "Color";
        }),
        temChildrenSize = attrValues.filter((item) => {
          return item.name == "Size";
        });
      for (let j = 0; j < temChildrenColor[0].values.length; j++) {
        choosedColors.push(temChildrenColor[0].values[j].id);
      }
      // console.log("choosedSizes-->>", temChildrenSize);
      for (let k = 0; k < temChildrenSize[0].values.length; k++) {
        choosedSizes.push(temChildrenSize[0].values[k].id);
      }
      this.selectSize = choosedSizes;
      this.selectColor = choosedColors;
      this.skuLists = skus.map((item, idx) => {
        if (item) {
          let info = {
            ...item,
          };

          info.status = item.status == 1;
          info.sort = idx + 1;
          info.color = this.getAttrs(item.attrValues, "Color");
          info.size = this.getAttrs(item.attrValues, "Size");
          return info;
        }
      });
      this.originSkuList = this.skuLists;
    },
    getNewArribute(ids, type) {
      let allList = this.AllAttributes.filter((item) => {
          return item.name == type;
        }),
        temValues = allList[0].values;
      let deslist = temValues.filter((item) => {
        return ids.includes(item.id);
      });
      this.afterHandleAttrData[type == "Size" ? 1 : 0] = {
        ...allList[0],
        values: deslist,
      };
    },
    // 组合属性
    attrCombination(ids, type) {
      this.getNewArribute(ids, type);
      let sizeArr = this.afterHandleAttrData[1];
      let colorArr = this.afterHandleAttrData[0];
      let attrValues = [];
      if (!this.selectColor.length || !this.selectSize.length) {
        this.skuLists = [];
        this.originSkuList = [];
        return;
      }
      if (sizeArr?.values?.length && colorArr?.values?.length) {
        for (let i = 0; i < sizeArr.values.length; i++) {
          for (let j = 0; j < colorArr.values.length; j++) {
            attrValues.push({
              attrId: colorArr.values[j].id + "_" + sizeArr.values[i].id,
              attrValues: [
                {
                  ...colorArr,
                  values: [colorArr.values[j]],
                },
                {
                  ...sizeArr,
                  values: [sizeArr.values[i]],
                },
              ],
            });
          }
        }
      }
      let hasIds = [];
      let originSkuList = JSON.parse(JSON.stringify(this.originSkuList));
      if (originSkuList?.length) {
        for (let i = 0; i < originSkuList.length; i++) {
          let attrArr = originSkuList[i].attrValues;
          let id = "";
          for (let j = 0; j < attrArr.length; j++) {
            for (let p = 0; p < attrArr[j].values.length; p++) {
              id += ((j == 1 && "_") || "") + attrArr[j].values[p].id;
            }
          }
          id && hasIds.push(id);
        }
      }
      attrValues = attrValues.filter((f) => !hasIds.includes(f.attrId));

      for (let i = 0; i < attrValues.length; i++) {
        originSkuList.push({
          cost: "",
          id: "",
          offlinePrice: "",
          onlinePrice: "",
          skuCode: "",
          spuCode: this.detailForm.spuCode,
          status: false,
          volume: "",
          weight: "",
          attrValues: attrValues[i].attrValues,
        });
      }
      // this.skuLists = originSkuList;
      this.skuLists = originSkuList.map((item, idx) => {
        if (item) {
          let info = {
            ...item,
          };
          info.status = item.status == 1;
          info.sort = idx + 1;
          info.size = this.getAttrs(item.attrValues, "Size");
          info.color = this.getAttrs(item.attrValues, "Color");
          return info;
        }
      });
      // console.log("skuLists>>>>>", this.skuLists);
    },
    colorSelectChange(ids) {
      this.attrCombination(ids, "Color");
    },
    sizeSelectChange(ids) {
      this.attrCombination(ids, "Size");
    },
    async getAttributeVals() {
      let res = await attributeValue({ type: 0 }),
        temList = res?.data,temColor = [],temSize =[],temShoe =[]
      for(let j =0;j<temList.length;j++){
        if(temList[j].name == 'Size'){
          temSize = temList[j].values
        }
        if(temList[j].name == 'Color'){
          temColor = temList[j].values
        }
        if(temList[j].name == 'Shoe size'){
          temShoe = temList[j].values
        }
      }
      this.AllAttributes = temList
      this.colorLists = temColor;
      this.sizeLists = temSize;
      this.shoeLists = temShoe
    },
    deleteNull(arr) {
      let list = [];
      arr.map((item) => {
        if (item.children == null) {
          delete item.children;
        } else {
          item.children = this.deleteNull(item.children);
        }
        list.push(item);
      });
      return list;
    },
    async getCategoryList() {
      let res = await categoryTree(),
        temList = res?.data;
      this.categoryTreeData = this.deleteNull(temList);
      // console.log("catory tree", this.categoryTreeData);
    },
    getAttrs(list, type) {
      // console.log('list',list,type)
      if (type == "Sort") {
        let tem = list.filter((item) => {
          return item.name == "Size";
        });
        return tem[0]?.values?.[0]?.sort;
      } else {
        let tem = list.filter((item) => {
            return item.name == type;
          }),
          tes = tem[0]?.values?.[0];
        return type == "Color" ? JSON.parse(tes?.value)?.rgbValue : tes?.value;
      }
    },
    editorChange(html) {
      this.editorDetl = html;
    },
    async save() {
      let form = deepCopy(this.detailForm)
      // console.log("form", form, this.afterHandleAttrData);
      if (this.skuLists.length == 0) {
        return this.$message.error("请添加商品SKU");
      }
      let temList = deepCopy(this.skuLists)
      for(let i =0;i<temList.length;i++){
        temList[i].status = temList[i].status ? 1: 0
        delete temList[i].color
        delete temList[i].size
      }

      let temSubImg = [],temDetailImg = [],temVideoUrl = []
      if(!Array.isArray(form.detailImg)){
        if(form.detailImg !=''){
          temDetailImg.push(form.detailImg)
        }else{
          temDetailImg = []
        }
      }else{
        temDetailImg = form.detailImg
      }
      if(!Array.isArray(form.subImg)){
        if(form.subImg !=''){
          temSubImg.push(form.subImg)
        }else{
          temSubImg = []
        }
      }else{
        temSubImg = form.subImg
      }
      if(!Array.isArray(form.videoUrl)){
        if(form.videoUrl !=''){
          temVideoUrl.push(form.videoUrl)
        }else{
          temVideoUrl = []
        }
      }else{
        temVideoUrl = form.videoUrl
      }
      try {
        productAdd({
          ...form,
          skus: temList,
          attrValues: this.afterHandleAttrData,
          description: this.editorDetl,
          subImg: temSubImg,
          detailImg: temDetailImg,
          videoUrl: temVideoUrl,
          id:this.productId
        }).then(res => {
          if (res?.success) {
            this.$message.success("保存成功");
            this.$router.replace({ path: "/product/list" });
          }else this.$message.error(res?.message)
        });
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>
<style scoped>
.title_detail {
  font-size: 20px;
  font-weight: 500;
  color: #000;
  margin-bottom: 20px;
}
.img_title {
  width: 100px;
  text-align: center;
}
.title_part {
  font-size: 16px;
  font-weight: 500;
  color: #000;
  margin: 12px 0;
}
</style>
